//
//  UserAccountViewModel.swift
//  CJPWB
//
//  Created by 陈锦彭 on 16/3/16.
//  Copyright © 2016年 chenjinpeng. All rights reserved.
//

import UIKit


class UserAccountViewModel {
    typealias successCallBack = (isSuccess : Bool) -> ()
      // MARK: - 属性
    ///单例
    static let shareInstance : UserAccountViewModel = UserAccountViewModel()
    ///模型
    var account : UserAccount?
    
    // MARK: - 计算属性
    ///判断是否有权限登陆
    var isLogin : Bool {
        
       return  account != nil && !isExprie
        
    }
    ///判断授权是否过期
    var isExprie : Bool {
        guard let expire = account?.overTime else {
            return false
        }
        
        return expire.compare(NSDate()) == NSComparisonResult.OrderedAscending
    
    }
    ///用户信息路径
    var filePath : String {
        let filePath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
       return (filePath as NSString).stringByAppendingPathComponent("account.plist")
    }
    
    // MARK: - 初始化
    init() {
        //读取数据
        account = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? UserAccount
    }
    
}




// MARK: - 发送网络请求获取access token
extension UserAccountViewModel {
    ///发送网络请求获取access token
     func getAccessToken(code : String, finished : successCallBack) {
        HttpRequestTool.shareInstance.requestAccessToken(code) { (successed, error) -> () in
            //1.错误校验
            if error != nil {
                print(error)
                return
            }
            //2.字典转模型
            guard let result = successed else {
                return
            }
            
            let account =  UserAccount(dict: result)
            
            //3.拿到access token去请求用户数据
            self.getUserInfo(account, finished: finished)
            
        }
    }
    
    ///拿到access token去请求用户数据
    private func getUserInfo(account : UserAccount, finished : successCallBack) {
        guard let access_token = account.access_token, uid = account.uid else {
            return
        }
        //3.1 设置请求参数
        let params = ["access_token" : access_token, "uid" : uid]
        //3.2发送请求
        HttpRequestTool.shareInstance.request(.GET, urlStr: "https://api.weibo.com/2/users/show.json", parameters: params, finished: { (success, error) -> () in
            //1.加载失败
            if error != nil {
                return
            }
            //2.加载成功
            guard let userInfodict = success else {
                return
            }
            //3.给用户模型赋值,保存数据
            account.avatar_large = userInfodict["avatar_large"] as? String
            account.screen_name = userInfodict["screen_name"] as? String
            //4.把用户数据归档
            NSKeyedArchiver.archiveRootObject(account, toFile: self.filePath)
            //5.把用户数据赋值给account
            self.account = account
            //6.成功的回调
            finished(isSuccess: true)
        })
        
        
    }
    
}
